import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/screen_util.dart';
import 'package:provider/provider.dart';
import 'package:shake_animation_widget/shake_animation_widget.dart';

import 'package:study_online/global/colors.dart';
import 'package:study_online/global/myIcons.dart';
import 'package:study_online/pages/courseStudyPage/views/PublishRemarkPage.dart';
import 'package:study_online/pages/discussPage/views/DiscussPage.dart';
import 'package:study_online/pages/studyPage/views/CourseCatalogueTab.dart';
import 'package:study_online/pages/studyPage/views/CourseIntroduceTab.dart';
import 'package:study_online/routes/CustomRoute.dart';
import 'package:flutter/material.dart';
import 'package:study_online/pages/studyPage/views/CourseRemarkTab.dart';
import 'package:video_player/video_player.dart';
import 'package:video_player_plus/video_player_plus.dart';
import 'package:study_online/entity/CourseRou.dart';
import '../CourseStudyViewModel.dart';
import 'TestTab.dart';
import 'VideoCatalogueTab.dart';

class CourseStudyPage extends StatefulWidget {
  CourseRou courseRou;

  CourseStudyPage(this.courseRou);

  @override
  _CourseStudyPageState createState() => _CourseStudyPageState();
}

class _CourseStudyPageState extends State<CourseStudyPage>
    with SingleTickerProviderStateMixin {
  TabController tabController;
  List<Tab> _tabs;
  List<Widget> _tabViews;

  @override
  void initState() {
    super.initState();
    _tabs = [
      Tab(text: "介绍"),
      Tab(text: "目录"),
      Tab(text: "测试"),
    ];
    _tabViews = [
      Container(
        color: Colors.white,
        child: CourseIntroduceTab(),
      ),
      Container(
        color: Colors.white,
        child: VideoCatalogueTab(),
      ),
      Container(
        color: Colors.white,
        child: TestTab(),
      ),
    ];
    this.tabController = TabController(length: _tabs.length, vsync: this);
  }

  @override
  Widget build(BuildContext context) {
    //debugPaintSizeEnabled=true;
    //CourseRou  _courseRou=ModalRoute.of(context).settings.arguments;
    print("###" + widget.courseRou.couId.toString());
    ScreenUtil.init(
      BoxConstraints(
          maxWidth: MediaQuery.of(context).size.width,
          maxHeight: MediaQuery.of(context).size.height),
      designSize: Size(1080, 2340),
    );
    return Stack(
      children: [
        Container(
          color: Colors.black,
          child: CustomScrollView(
            slivers: <Widget>[
              SliverPersistentHeader(
                pinned: true,
                delegate: SliverCustomHeaderDelegate(
                  title: widget.courseRou.couName,
                  collapsedHeight: ScreenUtil().setHeight(122),
                  expandedHeight: ScreenUtil().setHeight(630),
                  paddingTop: MediaQuery.of(context).padding.top,
                ),
              ),
              SliverPersistentHeader(
                pinned: true,
                delegate: StickyTabBarDelegate(
                  child: TabBar(
                    labelColor: Colors.black,
                    controller: this.tabController,
                    tabs: _tabs,
                  ),
                ),
              ),
              SliverFillRemaining(
                child: TabBarView(
                  controller: this.tabController,
                  children: _tabViews,
                ),
              ),
            ],
          ),
        ),
        buildContainer(context, widget.courseRou),
      ],
    );
  }
}

class SliverCustomHeaderDelegate extends SliverPersistentHeaderDelegate {
  final double collapsedHeight;
  final double expandedHeight;
  final double paddingTop;
  final String coverImgUrl;
  final String title;
  String statusBarMode = 'dark';

  SliverCustomHeaderDelegate({
    this.collapsedHeight,
    this.expandedHeight,
    this.paddingTop,
    this.coverImgUrl,
    this.title,
  });

  @override
  double get minExtent => this.collapsedHeight + this.paddingTop;

  @override
  double get maxExtent => this.expandedHeight;

  @override
  bool shouldRebuild(SliverPersistentHeaderDelegate oldDelegate) {
    return true;
  }

  void updateStatusBarBrightness(shrinkOffset) {
    if (shrinkOffset > 50 && this.statusBarMode == 'dark') {
      this.statusBarMode = 'light';
      SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(
        statusBarBrightness: Brightness.light,
        statusBarIconBrightness: Brightness.light,
      ));
    } else if (shrinkOffset <= 50 && this.statusBarMode == 'light') {
      this.statusBarMode = 'dark';
      SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(
        statusBarBrightness: Brightness.dark,
        statusBarIconBrightness: Brightness.dark,
      ));
    }
  }

  Color makeStickyHeaderBgColor(shrinkOffset) {
    final int alpha = (shrinkOffset / (this.maxExtent - this.minExtent) * 255)
        .clamp(0, 255)
        .toInt();
    return Color.fromARGB(alpha, 255, 255, 255);
  }

  Color makeStickyHeaderTextColor(shrinkOffset, isIcon) {
    if (shrinkOffset <= 50) {
      return isIcon ? Colors.white : Colors.transparent;
    } else {
      final int alpha = (shrinkOffset / (this.maxExtent - this.minExtent) * 255)
          .clamp(0, 255)
          .toInt();
      return Color.fromARGB(alpha, 0, 0, 0);
    }
  }

  @override
  Widget build(
      BuildContext context, double shrinkOffset, bool overlapsContent) {
    this.updateStatusBarBrightness(shrinkOffset);
    return Container(
      height: this.maxExtent,
      width: MediaQuery.of(context).size.width,
      child: Stack(
        fit: StackFit.expand,
        children: <Widget>[
          Container(
            child: VideoPlayerPlus(
              VideoPlayerController.network(
                  Provider.of<PublishRemarkViewModel>(context,listen: false).videoAdr),
              //VideoPlayerController.network("https://v-cdn.zjol.com.cn/276984.mp4"),
              //VideoPlayerController.network("http://192.168.43.173:8080/download?fileName=d28d40f.mp4"),
              // VideoPlayerController.file(file),
              key: ValueKey(Provider.of<PublishRemarkViewModel>(context,listen: false).videoAdr),
            ),
          ),
          Positioned(
            left: 0,
            top: this.maxExtent / 2,
            right: 0,
            bottom: 0,
            child: Container(
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  begin: Alignment.topCenter,
                  end: Alignment.bottomCenter,
                  colors: [
                    Color(0x00000000),
                    Color(0x90000000),
                  ],
                ),
              ),
            ),
          ),
          Positioned(
            left: 0,
            right: 0,
            top: 0,
            child: Container(
              color: this.makeStickyHeaderBgColor(shrinkOffset),
              child: SafeArea(
                bottom: false,
                child: Container(
                  height: this.collapsedHeight,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      IconButton(
                        icon: Icon(
                          Icons.arrow_back,
                          color: this
                              .makeStickyHeaderTextColor(shrinkOffset, true),
                        ),
                        onPressed: () => Navigator.pop(context),
                      ),
                      Text(
                        this.title,
                        style: TextStyle(
                          fontSize: 20,
                          fontWeight: FontWeight.w500,
                          color: this
                              .makeStickyHeaderTextColor(shrinkOffset, false),
                        ),
                      ),
                      IconButton(
                        icon: Icon(
                          MyIcons.share,
                          size: ScreenUtil().setSp(55),
                          color: this
                              .makeStickyHeaderTextColor(shrinkOffset, true),
                        ),
                        onPressed: () {},
                      ),
                    ],
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}

class StickyTabBarDelegate extends SliverPersistentHeaderDelegate {
  final TabBar child;

  StickyTabBarDelegate({@required this.child});

  @override
  Widget build(
      BuildContext context, double shrinkOffset, bool overlapsContent) {
    return Container(
      decoration: BoxDecoration(
        borderRadius: BorderRadius.only(
            topRight: Radius.circular(16), topLeft: Radius.circular(16)),
        color: Colors.white,
      ),
      child: this.child,
    );
    ;
  }

  @override
  double get maxExtent => this.child.preferredSize.height;

  @override
  double get minExtent => this.child.preferredSize.height;

  @override
  bool shouldRebuild(SliverPersistentHeaderDelegate oldDelegate) {
    return true;
  }
}

Container buildContainer(BuildContext context, CourseRou courseRou) {
  return Container(
    child: RoteFlowButtonMenu(
      //菜单图标组
      iconList: [
        Icon(Icons.cloud_download_outlined, color: Colors.white),
        Icon(Icons.group_sharp, color: Colors.white),
        Icon(Icons.assignment_turned_in_outlined, color: Colors.white),
        Icon(Icons.add, color: Colors.white),
      ],
      //菜单项所使用的背景颜色
      iconBackgroundColorList: [
        Colors.deepOrange,
        AppColors.primary,
        Color(0xff37A2E1),
        AppColors.yellow,
      ],
      //点击事件回调
      clickCallBack: (int index) {
        if (index == 0)
          print(0);
        else if (index == 1)
          Navigator.of(context).push(CustomRoute(DiscussPage(courseRou.couId)));
        else if (index == 2)
          Navigator.of(context)
              .push(CustomRoute(PublishRemarkPage(courseRou: courseRou)));
      },
      isLog: true,
    ),
  );
}
